package https;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.widget.RemoteViews;

import com.example.xuegengwang.xuegengwang.MainActivity;
import com.example.xuegengwang.xuegengwang.R;

import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.HashMap;

import common.Constant;
import common.MyApplication;
import https.callback.BaseDownLoadFileCallback;
import utils.FileUtils;
import utils.MyLogUtils;
import utils.SPUtils;

/**
 * Created by Administrator on 2017/6/15.
 * 下载文件
 */

public class DownLoadFileController {
    private static DownLoadFileController instance;
    private static final String TAG = "DownLoadFileController";
    private String downLoadingText = "";
    private String completeText = "";
    private String CompleteFilePath;//绝对路径

    public static DownLoadFileController getInstance() {
        if (instance == null) {
            instance = new DownLoadFileController();
        }
        return instance;
    }

    public String getDownLoadingText() {
        if (!TextUtils.isEmpty(downLoadingText)) {
            return downLoadingText;
        } else {
            return "今朝升学" + SPUtils.getSharedPreferences().getString(Constant.LAST_VERSION, "") + "正在下载中...";
        }
    }

    public void setDownLoadingText(String downLoadingText) {
        this.downLoadingText = downLoadingText;
    }

    public String getCompleteText() {
        if (!TextUtils.isEmpty(completeText)) {
            return completeText;
        } else {
            return "今朝升学" + SPUtils.getSharedPreferences().getString(Constant.LAST_VERSION, "") + "下载完成，点击打开";
        }
    }

    public void setCompleteText(String completeText) {
        this.completeText = completeText;
    }

    public void downLoad(final Context context, final String url, final HashMap<String, ?> dataMap, final String fileName, final int flag) {
        this.CompleteFilePath = Constant.APK_DIR + File.separator + fileName;
        MyLogUtils.e(TAG,Constant.APK_DIR + File.separator + fileName);
        final Intent downLoadIntent = new Intent(Constant.ACTION_DOWNLOAD_FILE);
        RequestParams requestParams = new RequestParams(url);
        requestParams.setConnectTimeout(5000);

        requestParams.setAutoRename(true);//断点下载
        requestParams.setSaveFilePath(CompleteFilePath);//设置保存地址
        x.http().get(requestParams, new BaseDownLoadFileCallback() {
            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                super.onLoading(total, current, isDownloading);
                MyLogUtils.e(TAG, "total" + total + "current" + current);
                downLoadIntent.putExtra("total", total);
                downLoadIntent.putExtra("current", current);
                upDateProgress(context, getDownLoadingText(), (int) total, (int) current, Constant.ACTION_DOWNLOAD_ING);
            }

            @Override
            public void onSuccess(File result) {
                super.onSuccess(result);
                downLoadIntent.putExtra("status", Constant.ACTION_DOWNLOAD_SUCCESS);
                MyApplication.getContext().sendBroadcast(downLoadIntent);
                Uri uri = Uri.fromFile(new File(CompleteFilePath));
                // 创建Intent意图
                Intent intent = new Intent(Intent.ACTION_VIEW);
                // 设置Uri和类型
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                // 执行意图进行安装
                context.startActivity(intent);
                upDateProgress(context, getCompleteText(), 100, 100, Constant.ACTION_DOWNLOAD_SUCCESS);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                downLoadIntent.putExtra("status", Constant.ACTION_DOWNLOAD_FILE_ERROR);
                MyApplication.getContext().sendBroadcast(downLoadIntent);
                MyLogUtils.e(TAG, "下载失败" + ex.toString());
                upDateProgress(context, "下载失败", 100, 100, Constant.ACTION_DOWNLOAD_FILE_ERROR);
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                super.onCancelled(cex);
                downLoadIntent.putExtra("status", Constant.ACTION_DOWNLOAD_CANCEL);
                MyApplication.getContext().sendBroadcast(downLoadIntent);
            }

            @Override
            public void onStarted() {
                super.onStarted();
                MyLogUtils.e(TAG, "onStarted----DownLoad---" + fileName);
                downLoadIntent.putExtra("status", Constant.ACTION_DOWNLOAD_STARTED);
                MyApplication.getContext().sendBroadcast(downLoadIntent);
                //先删除所有安装包
                FileUtils.getInstance().deleteDir(new File(Constant.APK_DIR));
                upDateProgress(context, getDownLoadingText(), 0, 0, Constant.ACTION_DOWNLOAD_STARTED);
            }
        });
    }

    private void upDateProgress(Context context, String text, int max, int current, String status) {
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.download_layout);
        Notification notification = new Notification();
        notification.icon = R.mipmap.ic_launcher;
        notification.tickerText = text;
        remoteView.setImageViewResource(R.id.image, R.mipmap.ic_launcher);
        notification.flags = Notification.FLAG_NO_CLEAR;
        notification.audioStreamType = android.media.AudioManager.ADJUST_LOWER;
        remoteView.setProgressBar(R.id.progressBar, max, current, false);
        remoteView.setTextViewText(R.id.download_tv, text);
        notification.contentView = remoteView;
        Intent i = new Intent();
        switch (status) {
            case Constant.ACTION_DOWNLOAD_SUCCESS:
                Uri uri = Uri.fromFile(new File(CompleteFilePath));
                // 创建Intent意图
                i.setAction(Intent.ACTION_VIEW);
                // 设置Uri和类型
                i.setDataAndType(uri, "application/vnd.android.package-archive");
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                // 执行意图进行安装
                notification.flags = Notification.FLAG_AUTO_CANCEL;
                break;
            default:
                i.setClass(context, MainActivity.class);
                break;
        }
        PendingIntent pendingintent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
        notification.contentIntent = pendingintent;
        manager.notify(0, notification);
    }
}
